package http

import (
	"net/http"

	"e-commerce/services/product-service/api/pb"
	"e-commerce/services/product-service/internal/service"

	"log"

	"github.com/gin-gonic/gin"
)

// var productService *service.ProductService
// var configPath string

// // 添加一个初始化函数
//
//	func Initialize(cfgPath string) {
//		log.Printf("Initializing with config path: %s", cfgPath)
//		configPath = cfgPath
//		productService = service.NewProductService(configPath)
//		log.Printf("Initialization completed")
//	}
func NewProductHandler(configPath string) *ProductHandler {
	log.Printf("Initializing with config path: %s", configPath)
	productService := service.NewProductService(configPath)
	log.Printf("Initialization completed")
	return &ProductHandler{
		ProductService: productService,
	}
}

type ProductHandler struct {
	ProductService *service.ProductService
}

// 采用gin框架实现
func (h *ProductHandler) GetProduct(c *gin.Context) {
	id := c.Param("id")
	product, err := h.ProductService.GetProductByID(id)
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
	}
	c.JSON(http.StatusOK, product)
}

func (h *ProductHandler) CreateProduct(c *gin.Context) {
	var product pb.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	id, err := h.ProductService.CreateProduct(&product)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusCreated, gin.H{"id": id})
}

func (h *ProductHandler) UpdateProduct(c *gin.Context) {
	id := c.Param("id")
	var product pb.Product
	if err := c.ShouldBindJSON(&product); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	err := h.ProductService.UpdateProduct(id, &product)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Product updated successfully"})
}

func (h *ProductHandler) DeleteProduct(c *gin.Context) {
	id := c.Param("id")
	err := h.ProductService.DeleteProduct(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "Product deleted successfully"})
}

func (h *ProductHandler) ListProducts(c *gin.Context) {
	category := c.Query("category")
	products, err := h.ProductService.ListProducts(category)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, products)
}
